#include "base.h"

//
// Time functions
//

#ifdef USE_API_BASE_POSIX

#include <unistd.h>
#include <sys/time.h>

float time_get(void)
{
    struct timeval cur_time;
    static struct timeval time_delta;

    gettimeofday(&cur_time, 0);

    // Check if called for the first time
    if(time_delta.tv_sec == 0)
    {
        // Set delta time
        time_delta.tv_sec = cur_time.tv_sec;
        time_delta.tv_usec = cur_time.tv_usec;
    }

    // Substract delta from time
    cur_time.tv_sec -= time_delta.tv_sec;
    cur_time.tv_usec -= time_delta.tv_usec;

    return cur_time.tv_sec + cur_time.tv_usec * 1.0e-6;
}

void time_sleep(float secs)
{
    // FIXME Implicit declaration for no apparent reason
    for(; secs > 0.5; secs -= 0.5)
    {
        usleep(5e5);
    }
    usleep(secs * 1.0e6);
    return;
}

void base_init(void)
{
    // Initialize timer
    time_get();
    return;
}

void base_exit(void)
{
    return;
}

#endif
